package uia.alumni.group;

import java.io.PrintWriter;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.http.HttpServletRequest;

import static uia.alumni.form.FieldType.*;
import static uia.alumni.web.Constants.*;
import static uia.alumni.group.Constants.*;

import uia.alumni.data.Group;
import uia.alumni.data.Role;
import uia.alumni.data.User;
import uia.alumni.form.*;
import uia.alumni.web.*;
import uia.alumni.exception.*;

/**
 * Show Groups.
 * @author Tri Vu
 */
public class ViewGroup extends Page {

    public static final String SERVLET_NAME = "group.view";
    @PersistenceUnit(name = PERSISTENCE_UNIT)
    private EntityManagerFactory emf;

    public ViewGroup() {
        super(Role.member);
    }

    @Override
    public void writeBody(PrintWriter out, HttpServletRequest request) {
        EntityManager em = emf.createEntityManager();

        try {
            Group group = getGroup(em, request);

            // Does the group exists?
            if (group != null) {
                boolean isAdmin = isAdmin(em, request);
                boolean isGroupOwner = isGroupOwner(em, request, group);

                // Vars for convinience
                String name = group.getName();
                String sgid = Long.toString(group.getId());
                
                // Print data
                out.println(tagH1(name));
                if(isAdmin){
                    out.println(getAdminInfo());
                    out.println("<ul>");
                    out.println(tagLi(tagA("#", "Delete "+name, GID, sgid)));
                    out.println("</ul>");
                    out.println("</div>");
                }
                if(isGroupOwner){
                    out.println("<p>You are the Owner of this group. You have the Options to change it. Delete members etc.</p>");
                    out.println(tagLi(tagA("#", "Edit "+name, GID, sgid)));
                }
                out.println("<dl>");
                out.println(tagDD("Name:", name));
                out.println(tagDD("Description: ", group.getInfo()));
                out.println("</dl>");
                out.println(tagH2("Members"));
                out.println("<ul>");
                for(User u : group.getMembers())
                    out.println(tagLi(u.getFullName()));
                out.println("</ul>");
                out.println(tagP(tagA(JoinGroup.SERVLET_NAME, "Join " + name, GID, sgid)));
                out.println(tagP(tagA(LeaveGroup.SERVLET_NAME, "LEAVE " + name, GID, sgid)));
            }
            else {
                throw new NotFoundException("The Group you are looking for does not exist");
            }
        } catch (Exception e) {
            addMessage(request, e.getMessage());
        } finally {
            //
        }
    }
}
